package com.oocl.shopping.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oocl.shopping.pojo.Customer;
import com.oocl.shopping.service.CustomerService;
import com.oocl.shopping.service.impl.CustomerServiceImpl;
import com.oocl.shopping.util.Log4jUtil;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CustomerService service;   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
    	service = new CustomerServiceImpl();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接参
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		//校验
		if(!service.isNameFmt(name)){
			response.sendRedirect("login.jsp");
			return;
		}
		//转型
		//封装
		Customer cust = service.findCustomer(name, pwd);
		
		if(cust != null){
			HttpSession sen = request.getSession();
			sen.setAttribute("cust", cust);
			Log4jUtil.getLogger().info("[ login ] "+ name+" "+ cust+" "+ "logined ");
			response.sendRedirect("view/showbooks.jsp");
		}else{
			request.setAttribute("errorInfo", "Sorry, user name or password is not right. please login again");
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
